/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentFieldValue;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.ContentFieldManager;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentFieldValueForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>Deletes content field value
 * </p>
 * <p><a href="DeleteContentFieldValueAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.29 $ $Date: 2008/02/06 14:37:34 $
 * @struts.action path="/core/contentFieldValue/delete"
 * name="contentFieldValueForm"
 * scope="request"
 * validate="false"
 * roles="core-contentFieldValue-delete"
 * @struts.action-forward name="listContentFieldValues"
 * path="/core/contentFieldValue/list.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentFieldValue/list.do"
 */
public final class DeleteContentFieldValueAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		ContentFieldValueForm contentFieldValueForm = (ContentFieldValueForm) form;
		Long contentFieldId;
		if ( !GenericValidator.isBlankOrNull(contentFieldValueForm.getContentFieldId()) ) {
			contentFieldId = Long.valueOf(contentFieldValueForm.getContentFieldId());
		} else if ( request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY) != null ) {
			contentFieldId = (Long) request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content field ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		List cfvLocales;

		if ( request.getAttribute(WebappConstants.CONTENT_FIELD_VALUE_SELECTED_LOCALES_KEY) != null ) {
			cfvLocales = (List) request.getAttribute(WebappConstants.CONTENT_FIELD_VALUE_SELECTED_LOCALES_KEY);
		} else if ( !GenericValidator.isBlankOrNull(request.getParameter("locale")) ) {
			String locale = request.getParameter("locale");
			cfvLocales = new ArrayList();
			cfvLocales.add(locale);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content field value locale. Returning to list...");
			}
			return mapping.findForward("listContentFieldValues");
		}

        Localizable owner = null;
        boolean cfvInDefaultLocaleDeletedForPage = false;
        CacheUtil cacheUtil = CacheUtil.getInstance(request);

        ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);
        ContentField contentField = null;
		boolean alreadyDeletedExist = false;
        Set pagesToSave = new HashSet();
        for ( int i = 0; i < cfvLocales.size(); i++ ) {
			String localeIdentifier = (String) cfvLocales.get(i);
			ContentFieldValue contentFieldValue = contentFieldManager.findContentFieldValueByContentFieldIdAndLocale(contentFieldId, localeIdentifier);
			if ( contentFieldValue == null ) {
				alreadyDeletedExist = true;
			} else {

				if ( contentField == null ) {
					contentField = contentFieldValue.getContentField();
					contentFieldId = contentField.getId();
                    owner = contentField.getOwner();
                }

				contentFieldManager.deleteContentFieldValue(contentFieldValue.getId());

				// flush the cache and unindex
				cacheUtil.flushFieldIndices();
				SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());

				if ( owner instanceof Layout ) {
					Layout layout = (Layout) owner;
					cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

					//TODO: unindex search index for every content page of the layout.
					//TODO: unindex action pages
					List contentPages = layout.getContentPages();
					for ( int j = 0; j < contentPages.size(); j++ ) {
						ContentPage contentPage = (ContentPage) contentPages.get(j);
						searchManager.reIndexPage(contentPage, request);
						cacheUtil.updateContentPageLastModifiedInCache(contentPage.getUri());
					}
				} else if ( owner instanceof Page ) {
					Page page = (Page) owner;
					cacheUtil.flushPageFieldValueCache(page.getUri(), contentField.getIdentifier(), localeIdentifier);
					searchManager.reIndexPage(page, request);
					if ( page instanceof ContentPage ) {
						cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
					}
                    if (contentFieldValue.getContentLocale().getDefaultInstance().booleanValue()) {
                        cfvInDefaultLocaleDeletedForPage = true;
                    }
                    page.setLastUpdatedDatetime(new Date());
                    pagesToSave.add(page);
                }
			}
		}

        // saving pages which last updated date time has been updated
        PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
        for (Iterator pageIterator = pagesToSave.iterator(); pageIterator.hasNext(); ) {
            Page page = (Page) pageIterator.next();
            pageManager.updatePage(page);
        }

        // CFV in default locale has been deleted, so flush cache for all
        // locales for which there is no CFV (because for them CFV in
        // default language is used)
        if (cfvInDefaultLocaleDeletedForPage) {
            ServletContext servletContext = servlet.getServletContext();
            Page page = (Page) owner;
            LocaleUtil localeUtil = LocaleUtil.getInstance(servletContext);
            List locales = localeUtil.getAvailableLocales();
            Iterator localeIterator = locales.iterator();
            while (localeIterator.hasNext()) {
                ContentLocale contentLocale = (ContentLocale) localeIterator.next();
                String localeIdentifier = contentLocale.getIdentifier();
                ContentFieldValue anotherValue = (ContentFieldValue) contentField.getContentFieldValuesMap().get(localeIdentifier);
                if (anotherValue == null) {
                    // no value for this language, so flush its cache
                    // because CFV in default locale has been deleted
                    cacheUtil.flushPageFieldValueCache(page.getUri(), contentField.getIdentifier(), localeIdentifier);
                }
            }
        }

        request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_ID_KEY, contentFieldId);

		if ( alreadyDeletedExist ) {
			ActionMessages errors = new ActionMessages();
			errors.add("someValuesDeleted", new ActionMessage("core.contentFieldValue.errors.someValuesDeleted"));
			saveErrors(request, errors);
		}

		return mapping.findForward("listContentFieldValues");
	}
}